<template>
  <div class="container-fluid">
    <div class="card">
      <div class="card-header">
        <h3 class="card-title">卡路里监测</h3>
        <div class="card-tools">
          <button class="btn btn-primary" @click="fetchData">
            <i class="fa fa-refresh mr-1"></i>刷新数据
          </button>
        </div>
      </div>
      <div class="card-body">
        <div class="row">
          <div class="col-lg-6 mb-4">
            <chart-card title="卡路里摄入与消耗趋势" :chart-data="calorieTrendData" chart-type="line" />
          </div>
          <div class="col-lg-6 mb-4">
            <chart-card title="营养成分分布" :chart-data="nutritionDistributionData" chart-type="pie" />
          </div>
        </div>
        <div class="row">
          <div class="col-lg-12">
            <div class="card">
              <div class="card-header">
                <h3 class="card-title">添加饮食记录</h3>
              </div>
              <div class="card-body">
                <form @submit.prevent="addRecord" ref="recordForm">
                  <div class="row">
                    <div class="col-md-4">
                      <div class="form-group">
                        <label for="foodName">食物名称</label>
                        <input type="text" id="foodName" v-model="newRecord.foodName" class="form-control" required>
                        <div class="invalid-feedback" v-show="errors.foodName">
                          {{ errors.foodName }}
                        </div>
                      </div>
                    </div>
                    <div class="col-md-2">
                      <div class="form-group">
                        <label for="calories">卡路里 (kcal)</label>
                        <input type="number" id="calories" v-model.number="newRecord.calories" class="form-control" required>
                        <div class="invalid-feedback" v-show="errors.calories">
                          {{ errors.calories }}
                        </div>
                      </div>
                    </div>
                    <div class="col-md-2">
                      <div class="form-group">
                        <label for="protein">蛋白质 (g)</label>
                        <input type="number" id="protein" v-model.number="newRecord.protein" class="form-control">
                        <div class="invalid-feedback" v-show="errors.protein">
                          {{ errors.protein }}
                        </div>
                      </div>
                    </div>
                    <div class="col-md-2">
                      <div class="form-group">
                        <label for="carbs">碳水化合物 (g)</label>
                        <input type="number" id="carbs" v-model.number="newRecord.carbs" class="form-control">
                        <div class="invalid-feedback" v-show="errors.carbs">
                          {{ errors.carbs }}
                        </div>
                      </div>
                    </div>
                    <div class="col-md-2">
                      <div class="form-group">
                        <label for="fat">脂肪 (g)</label>
                        <input type="number" id="fat" v-model.number="newRecord.fat" class="form-control">
                        <div class="invalid-feedback" v-show="errors.fat">
                          {{ errors.fat }}
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="row">
                    <div class="col-md-6">
                      <div class="form-group">
                        <label for="mealType">餐别</label>
                        <select id="mealType" v-model="newRecord.mealType" class="form-control">
                          <option value="breakfast">早餐</option>
                          <option value="lunch">午餐</option>
                          <option value="dinner">晚餐</option>
                          <option value="snack">零食</option>
                        </select>
                      </div>
                    </div>
                    <div class="col-md-6">
                      <div class="form-group">
                        <label for="date">日期</label>
                        <input type="date" id="date" v-model="newRecord.date" class="form-control" required>
                        <div class="invalid-feedback" v-show="errors.date">
                          {{ errors.date }}
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="form-group">
                    <label for="notes">备注</label>
                    <textarea id="notes" v-model="newRecord.notes" class="form-control" rows="2"></textarea>
                  </div>
                  <button type="submit" class="btn btn-success">
                    <i class="fa fa-plus mr-1"></i>添加记录
                  </button>
                </form>
              </div>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-lg-12">
            <div class="card">
              <div class="card-header">
                <h3 class="card-title">最近饮食记录</h3>
              </div>
              <div class="card-body">
                <div class="table-responsive">
                  <table class="table table-bordered table-striped">
                    <thead>
                      <tr>
                        <th>食物名称</th>
                        <th>卡路里 (kcal)</th>
                        <th>蛋白质 (g)</th>
                        <th>碳水化合物 (g)</th>
                        <th>脂肪 (g)</th>
                        <th>餐别</th>
                        <th>日期</th>
                        <th>操作</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="record in recentRecords" :key="record.id">
                        <td>{{ record.foodName }}</td>
                        <td>{{ record.calories }}</td>
                        <td>{{ record.protein }}</td>
                        <td>{{ record.carbs }}</td>
                        <td>{{ record.fat }}</td>
                        <td>{{ getMealTypeName(record.mealType) }}</td>
                        <td>{{ formatDate(record.date) }}</td>
                        <td>
                          <button class="btn btn-danger btn-sm" @click="deleteRecord(record.id)">
                            <i class="fa fa-trash"></i>
                          </button>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import ChartCard from '@/components/ChartCard.vue'
import { dateFormat } from '@/utils/dateUtil'
import { validatePositiveNumber } from '@/utils/validationUtil'

export default {
  name: 'CalorieTracker',
  components: {
    ChartCard
  },
  data() {
    return {
      newRecord: {
        foodName: '',
        calories: 0,
        protein: 0,
        carbs: 0,
        fat: 0,
        mealType: 'breakfast',
        date: new Date().toISOString().split('T')[0],
        notes: ''
      },
      errors: {}
    }
  },
  computed: {
    ...mapGetters('calorieTracker', ['recentRecords', 'calorieTrendData', 'nutritionDistributionData']),
    mealTypes() {
      return [
        { value: 'breakfast', label: '早餐' },
        { value: 'lunch', label: '午餐' },
        { value: 'dinner', label: '晚餐' },
        { value: 'snack', label: '零食' }
      ]
    }
  },
  methods: {
    ...mapActions('calorieTracker', ['fetchCalorieData', 'addCalorieRecord', 'deleteCalorieRecord']),
    async fetchData() {
      try {
        await this.fetchCalorieData()
        this.$message.success('数据刷新成功')
      } catch (error) {
        this.$message.error('数据刷新失败: ' + error.message)
      }
    },
    validateForm() {
      this.errors = {}
      let isValid = true

      if (!this.newRecord.foodName.trim()) {
        this.errors.foodName = '食物名称不能为空'
        isValid = false
      }

      if (this.newRecord.calories === undefined || this.newRecord.calories <= 0) {
        this.errors.calories = '卡路里必须为正数'
        isValid = false
      } else if (!validatePositiveNumber(this.newRecord.calories)) {
        this.errors.calories = '卡路里必须为有效的数字'
        isValid = false
      }

      if (this.newRecord.protein < 0) {
        this.errors.protein = '蛋白质不能为负数'
        isValid = false
      } else if (this.newRecord.protein && !validatePositiveNumber(this.newRecord.protein)) {
        this.errors.protein = '蛋白质必须为有效的数字'
        isValid = false
      }

      if (this.newRecord.carbs < 0) {
        this.errors.carbs = '碳水化合物不能为负数'
        isValid = false
      } else if (this.newRecord.carbs && !validatePositiveNumber(this.newRecord.carbs)) {
        this.errors.carbs = '碳水化合物必须为有效的数字'
        isValid = false
      }

      if (this.newRecord.fat < 0) {
        this.errors.fat = '脂肪不能为负数'
        isValid = false
      } else if (this.newRecord.fat && !validatePositiveNumber(this.newRecord.fat)) {
        this.errors.fat = '脂肪必须为有效的数字'
        isValid = false
      }

      if (!this.newRecord.date) {
        this.errors.date = '日期不能为空'
        isValid = false
      }

      return isValid
    },
    async addRecord() {
      if (!this.validateForm()) {
        return
      }

      try {
        await this.addCalorieRecord(this.newRecord)
        this.$message.success('添加记录成功')
        this.resetForm()
        this.fetchData()
      } catch (error) {
        this.$message.error('添加记录失败: ' + error.message)
      }
    },
    async deleteRecord(id) {
      if (confirm('确定要删除这条记录吗？')) {
        try {
          await this.deleteCalorieRecord(id)
          this.$message.success('删除记录成功')
          this.fetchData()
        } catch (error) {
          this.$message.error('删除记录失败: ' + error.message)
        }
      }
    },
    resetForm() {
      this.newRecord = {
        foodName: '',
        calories: 0,
        protein: 0,
        carbs: 0,
        fat: 0,
        mealType: 'breakfast',
        date: new Date().toISOString().split('T')[0],
        notes: ''
      }
      this.errors = {}
    },
    getMealTypeName(type) {
      const mealType = this.mealTypes.find(t => t.value === type)
      return mealType ? mealType.label : type
    },
    formatDate(dateString) {
      return dateFormat(dateString, 'YYYY-MM-DD')
    }
  },
  created() {
    this.fetchData()
  }
}
</script>

<style scoped>
.invalid-feedback {
  display: block;
  color: #dc3545;
}
</style>    